package com.databias.util;

public class RollingAverage {

	private int sample = 5;
	private int runningAverage = 0;
	private int count =0;
	private int bias=1;
	private boolean threshold=false;
	

	/**
	 * Create a rolling averaged with sampsize history
	 * @param sampsize
	 */
	public RollingAverage(int sampsize)
	{
		if ((sampsize<=0)||(sampsize>10)) sampsize=sample;

		sample=sampsize;
	}
	
	/**
	 * Constructor to set up an average with a bias
	 * @param sampsize
	 * @param newbias
	 */
	public RollingAverage(int sampsize, int newbias)
	{
		if ((sampsize<=0)||(sampsize>10)) sampsize=sample;
		sample=sampsize;
		
		if ((newbias<=0)||(newbias>10)) newbias=1;
		bias=newbias;
		
	}
	
	public int getAverage() {
		
		return runningAverage;
	}

	public int getAverage(int newNumber) {
		
		// If we have fewer than our sample size, don't skew
		if (!threshold)
		{
			if (!threshold) count++;
			if (count>=sample) threshold=true;
		
			return runningAverage = 
				(runningAverage * count + newNumber * bias) / (count + 1);
		}

		return runningAverage = 
			(runningAverage * sample + newNumber * bias) / (sample + 1);
	}
}
